<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Exception;

class TestController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'Test';
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = [$param['keyword_type'], 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['date_value']) && $param['date_value']) {
            $rangeDate = $param['date_value'];
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = [$param['time_type'], '>=', $startTime];
            $where[] = [$param['time_type'], '<=', $endTime];
        }

        return $where;
    }

    /**
     * 导出
     */
    public function export(Request $request)
    {
        set_time_limit(300); // 超时
        ini_set('memory_limit', '1024M'); // 内存溢出

        $param = $request->all();
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $where = [
            ['id', '<', '100001']
        ];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        $data = $model->where($where)->orderBy('created_at', 'asc')->forPage($param['page'],$param['limit'])->get()->toArray(); // 查询1万条会出错
        $merges = [];
        $mergeField = 'created_at';
        foreach ($data as $item) {
            if (isset($merges[$item[$mergeField]])) {
                $merges[$item[$mergeField]]['total'] += 1;
                $merges[$item[$mergeField]]['count'] += 1;
            } else {
                $merges[$item[$mergeField]]['total'] = 1;
                $merges[$item[$mergeField]]['count'] = 1;
            }

        }
        foreach ($data as $key => &$item) {
            $item['number'] = ($key + 1) * 10000;
            if (isset($merges[$item[$mergeField]])) {
                $merges[$item[$mergeField]]['count'] -= 1;
            }
            // 合并行
            if ($merges[$item[$mergeField]]['count'] == 0) {
                $item['created_at_rowspan'] = $merges[$item[$mergeField]]['total'];
            } else {
                $item['created_at_rowspan'] = 0;
            }

            // 合并列
            if ($key % 3 == 0) {
                //$item['id'] = '';
                $item['number_colspan'] = 2;
            } else {
                $item['number_colspan'] = 0;
            }
            // 背景色
            if ($key % 2 == 0) {
                $item['admin_id_bgColor'] = 'ffb400';
            } else {
                $item['info_fontColor'] = '00b42a';
            }
            // 加粗
            if ($key % 2 == 0) {
                $item['admin_id_bold'] = false;
                $item['info_bold'] = true;
            } else {
                $item['admin_id_bold'] = true;
                $item['info_bold'] = false;
            }
            // 行高【不能与 wrapText 同时设置】
            if ($key % 2 == 0) {
                $item['height'] = 22;
            } else {
                $item['height'] = 14;
            }
        }

        $cellName = [
            [
                'title' => '序号',
                'field' => 'number',
                'width' => 8,
                'colspanField' => 'number_colspan', // 合并列
                'alignCenter' => 'center',
            ],
            ['title' => 'ID', 'field' => 'id', 'width' => 8],
            [
                'title' => '管理员',
                'field' => 'admin_id',
                'width' => 14, // 宽
                // 'rowspanField' => 'admin_id_rowspan', // 合并行
                'bgColorField' => 'admin_id_bgColor', // 背色
                'boldField' => 'admin_id_bold', // 加粗
                'alignCenter' => 'center', // 设置居中
            ],
            ['title' => '名称', 'field' => 'name', 'width' => 16],
            [
                'title' => '详情',
                'field' => 'info',
                'width' => 30,
                'fontColorField' => 'info_fontColor', // 字体色
                'boldField' => 'info_bold',
                //'wrapText' => true, // 自动换行
            ],
            [
                'title' => '创建时间',
                'field' => 'created_at',
                'width' => 20,
                'rowspanField' => 'created_at_rowspan', // 合并行
            ],
        ];
        $options = [
            //'sheetDatas' => $sheetDatas, 多个 sheet
            'print' => true, // 打印
            'border' => true, // 单元格边框
            // 表头设置
            'headers' => [
                'height' => '20', // 行高
            ],
        ];

        $filePath = config('path.upload_path') . 'csv/test/' . date('Y-m') . '/' . date('d');
        $fileName = $filePath . '/test_' . date('YmdHis');

        $result = \App\Services\Excel::exportExcel('测试', $data, $cellName, $filePath, $fileName, $options, false);
        //$result = \App\Services\Excel::export('测试', $model, $where, $cellName, $filePath, $fileName);
        if ($result['status'] != 1) {
            return api_response(self::STATUS_ERROR, $result['msg'], []);
        }

        $data = [
            'filename' => $fileName,
            'url' => $result['url']
        ];

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
    }
}
